package cn.stronglink.esm27.collection.iot.devices.esm27.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.ESM27ResponseMessageEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.WindEntity;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

public class GetWindRealtimeDatasReturnHandle implements IMessageHandle<ESM27ResponseMessageEntity, Object> {
	private static Logger logger = LogManager.getLogger(GetDeviceRealtimeDataReturnHandle.class.getName());
	private final static String ACTION_CODE="GetWindRealtimeDatasReturn";
	private final static String TOPIC_NAME="ESM27ToService";		// MQ发送主题
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	
	@Override
	public boolean isHandle(ESM27ResponseMessageEntity t) {
		if(t.getCommandCode()==0x05 && t.getDatas().length==28) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ESM27ResponseMessageEntity t) {
		WindEntity we =new WindEntity();
		we.setWindSpeed(ByteUtil.bytesToFloat(t.getDatas(), 0));
		we.setWinDirection(ByteUtil.bytesToFloat(t.getDatas(), 4));
		we.setTemperature(ByteUtil.bytesToFloat(t.getDatas(), 8));
		we.setHumidity(ByteUtil.bytesToFloat(t.getDatas(), 12));
		we.setPressure(ByteUtil.bytesToFloat(t.getDatas(), 16));
		we.setPm2_5(ByteUtil.bytesToFloat(t.getDatas(), 20));
		we.setNoise(ByteUtil.bytesToFloat(t.getDatas(), 24));
		we.setDeviceAddress(t.getDeviceAddress());
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(ACTION_CODE);
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(we);
		message.setIsSuccess(true);
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME, json);
		logger.info("发送获取风力实时数据到MQ完成:{}",json);
		return null;
	}

}